//
//  UIButton+Utility.swift
//  iHear
//
//  Created by wei.feng on 2023/6/15.
//

import UIKit

extension UIButton {
    
    static func create(title: String? = nil,
                       font: UIFont? = nil,
                       titleColor: UIColor? = nil,
                       icon: String? = nil,
                       bgImage: String? = nil,
                       bgColor: UIColor? = nil
    ) -> UIButton {
        
        let view = UIButton(type: .custom)
        view.backgroundColor = bgColor
        view.setTitle(title, for: .normal)
        view.titleLabel?.font = font
        view.setTitleColor(titleColor, for: .normal)
        if let icon = icon {
            view.setImage(UIImage(named: icon), for: .normal)
        }
        if let bgImage = bgImage {
            view.setBackgroundImage(UIImage(named: bgImage), for: .normal)
        }        
        return view
    }
}

private var clickDelayTime = "clickDelayTime"
private var lastClickTimeKey = "lastClickTimeKey"

extension UIButton {
    
    /// 上一次点击时间
    var lastClickTime: TimeInterval {
        set {
            objc_setAssociatedObject(self, &lastClickTimeKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            if let time = objc_getAssociatedObject(self, &lastClickTimeKey) as? TimeInterval {
                return time
            }
            return 0.0
        }
    }

    /// 每两次点击最小间隔时间
    var delayTime: TimeInterval {
        set {
            objc_setAssociatedObject(self, &clickDelayTime, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            if let clickDelayTime = objc_getAssociatedObject(self, &clickDelayTime) as? TimeInterval {
                return clickDelayTime
            }
            return 0.0
        }
    }
    
    open override func sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
        
        // 未设置delayTime值或者设置为0s间隔
        if delayTime == 0 {
            super.sendAction(action, to: target, for: event)
        } else {
            // 这里当前点击时刻用timeIntervalSince1970作为参考值，也可以取其他
            // 两次点击时间间隔大于设定值，响应
            let currentTime = Date().timeIntervalSince1970
            if currentTime - lastClickTime > delayTime {
                super.sendAction(action, to: target, for: event)
                // 更新本次点击时刻
                lastClickTime = currentTime
            }
        }
    }
}
